const Koa = require('koa');
const app = new Koa();
const bodyparser = require('koa-bodyparser');
//引入读取文件的模块
const fs = require('fs');

app.use(bodyparser());

app.use(async(ctx)=>{
    let url = ctx.request.url;
    let html = await route(url);
    console.log(html);
    ctx.body = html;
});

async function route(url) {
    let page = '404.html';
    switch (url) {
        case '/':
            page='index.html';
            break;
        case '/index':
            page='index.html';
            break;
        case '/todo':
            page='todo.html';
            break;
        default:
            break;
    }

    let html = await render(page);
    return html;
}

function render(page) {
    return new Promise((resolve,reject) => {
        let pageUrl = './page/' + page;
        fs.readFile(pageUrl,"utf-8",(err,data) => {
            if(err) {
                reject(err);
            }else {
                resolve(data);
            }
        });
    });
}

// 监听端口
app.listen(3000,() => {
    //监听回调
    console.log('app is start at port 3000');
});
